<template>
  <div
    style="margin-top: 15px;min-height: 100%;"
    class="main-div"
  >
    <Spin v-show="isSpinShow" fix size="large"/>
    <el-tabs v-model="activeName" >
      <el-tab-pane label="基本信息" name="form">
        <div v-if="jsonData.config!=null" class="container"   style=" overflow: auto;max-height: 550px">
          <fm-generate-form
            ref="generateForm"
            :data="jsonData"
            :remote="remoteFuncs"
            :value="editData"
            :remote-option="dynamicData"
          />

        </div>
      </el-tab-pane>
      <el-tab-pane label="附件" name="second">

        <el-form ref="attachmentForm" :model="attachmentForm" label-width="80px">
          <el-row class="table_form">
            <el-col :span="12">
              <el-form-item label="创建人" prop="createBy">
                <el-input v-model="attachmentForm.createBy" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间" prop="createTime">
                <el-input v-model="attachmentForm.createTime" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="内容" prop="changeContent">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="attachmentForm.changeContent">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="附件" prop="code">

                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :before-upload="uploadform"
                  :action="baseUploadURL"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="upFile"
                  :file-list="fileList"
                  :auto-upload="true">
                  <el-button type="primary">上传<i class="el-icon-upload el-icon--right"></i></el-button>

                  <div slot="tip" class="el-upload__tip"></div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" prop="code">

                <el-button size="small" type="success" @click="submitForm">保存</el-button>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </el-tab-pane>
      <el-tab-pane label="流程图" name="view">

        <app v-if="startForm.modelId!=null && startForm.modelId!=''" style="min-height: 450px" :viewData="xml"></app>

      </el-tab-pane>
    </el-tabs>


    <Modal
      :mask-closable="false"
      v-model="flowImage.show"
      title="流程图"
      width="85%"
      :transfer="false"
    >
      <iframe
        id="flowImageframe"
        width="100%"
        style="min-height: 600px"
        height="100%"
        frameborder="0"
        align="center"
        allowfullscreen="true"
        allow="autoplay"
        :src="flowImage.src"
      />
    </Modal>
  </div>

</template>

<script>
  import {addAttachment, getStartBtn, loadWfModule, renderStartForm, saveDraft, startDef} from '@/api/loadwfmodule'
  import IframeUrl from '@/components/plug/IframeUrl'
  import App from './App'

  export default {
    name: 'Task',
    components: {
      IframeUrl,
      App
    },

    data() {
      return {
        baseUploadURL: process.env.VUE_APP_BASE_BPM_API + "/a1bpmn/api/upload/drl",
        fileList: [],
        fileListAdd: [],
        attachmentForm: {
          createBy: '',
          id: '',
          createTime: '',
          procDefId: '',
          changeContent: '',
          modelKey: '',
          file: [],
        },
        baseURL: process.env.VUE_APP_BASE_BPM_API,
        viewImageModelerTmpSrc: this.baseURL + "view/def.html?&modelId=100" ,
        activeName: 'form',
        tableData: [],
        jsonData: {},
        built: {},
        editData: {},
        remoteFuncs: {},
        singleUserData: {},
        dynamicData: {},
        sysTypeEntity: {},
        isSpinShow: true,
        taskBtns: [],
        modelKey: '',
        tableHeight: 450,
        formData_e: null,
        xml: null,
        formIndex: false,
        startForm: {
          defId: '',
          attachmentId: '',
          modelId: 0,
          typeTitle: '',
          formData: '',
          groupId: '',
          typeKey: '',
          defKey: ''
        },
        flowImage:
          {
            show: false,
            src: '',
            base: process.env.VUE_APP_BASE_BPM_API + '/view/def.html?fireHoverAction=true&modelId='
          }

      }
    },
    mount() {
      this.getData()
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop

    },
    created: function () {
      this.activeName='form'

      var query = this.$route.query
      if (query.modelKey) {
        this.modelKey = query.modelKey
        this.attachmentForm.modelKey = query.modelKey
        this.attachmentForm = {
          createBy: '',
          id: '',
          createTime: '',
          procDefId: '',
          changeContent: '',
          modelKey: '',
          file: [],
        }

      } else {
        if (this.operateModelKey) {
          this.formIndex = true
          this.modelKey = this.operateModelKey
        }
      }
      this.startForm.defKey = this.modelKey
      this.getData()

    },
    watch: {
      operateModelKey() {
        this.activeName='form'

        if (this.operateModelKey) {
          this.modelKey = this.operateModelKey
          this.formIndex = true
          this.getData()
        } else {
          this.jsonData = {}
          this.editData = {}
          this.formIndex = false;
          this.modelKey = ""
        }
        this.startForm.defKey = this.modelKey


      },
      jsonData: {
        handler(newValue, oldValue) {
          if (newValue) {
            this.getFormData()
          }
        },
        deep: true
      }
    },
    props: {
      operateModelKey: {
        type: String,
        default: ""
      }
    },
    methods: {
      /** 提交按钮 */
      submitForm() {
        this.$refs["attachmentForm"].validate(valid => {
          var formData = new FormData();//new一个formData事件
          for (var i = 0; i < this.attachmentForm.file.length; i++) {
            formData.append('files', this.attachmentForm.file[i]);
          }

          formData.append("procDefId", this.attachmentForm.procDefId);
          formData.append("changeContent", this.attachmentForm.changeContent);
          formData.append("modelKey", this.modelKey);
          if (this.attachmentForm.id) {
            formData.append("id", this.attachmentForm.id);
          }

          if (valid) {
            addAttachment(formData).then(response => {
              if (response.code == 0) {
                this.attachmentForm.id=response.msg
                this.startForm.attachmentId = this.attachmentForm.id;

                this.msgSuccess("操作成功");
              }

            });
          }
        });
      },
      handleRemove(file, fileList) {
        this.attachmentForm.file = fileList
      },
      handlePreview(file) {
      },
      uploadform: function (file) {
        if (!this.attachmentForm.file) {
          this.attachmentForm.file = []
        }
        this.attachmentForm.file.push(file)
      },
      /* 上传文件操作 */
      upFile(res, file) {
      },
      action: function (action) {
        if (typeof action === 'object') {
          this.alias = action.alias
        } else {
          this.alias = action
        }

        switch (this.alias) {
          case 'startFlow':// 启动
            this.startFlow()
            break
          case 'flowImage':
            this.flowImageAction()
            break
          case 'print':

            window.print()
            break
          case 'saveDraft':
            this.saveDraft()
            break
          default:
        }
      },
      flowImageAction: function () {
        this.flowImage.src = this.flowImage.base + this.startForm.modelId + '&t=' + new Date().getTime()
        this.flowImage.show = true
      },
      startFlow: function () {
        this.getFormData()
        const that = this
        if (this.$refs.generateForm) {
          this.$refs.generateForm.getData().then(data => {
            this.startForm.formData = JSON.stringify(data)
            this.formData_e = null

            startDef(that.startForm).then((response) => {
              if (response.code == 0) {

                that.go()
                this.$store.dispatch('user/SetToDoCount')
              } else {
                this.$message({"duration": '800', message: response.msg, type: 'warning', customClass: 'zZindex'});

              }
            })


          }).catch(e => {
            this.$message({"duration": '800', message: '表单校验不通过', type: 'warning', customClass: 'zZindex'});

          })
        }


      },

      async saveDraft() {
        var formData = {}
        const get = () => {
          return new Promise(resolve => {
            formData = this.getFormData()
            resolve(formData)
          })
        }

        await get()
        const that = this
        var obj = JSON.parse(JSON.stringify(this.startForm))
        obj['formDataStr'] = obj['formData']
        delete (obj['formData'])

        saveDraft(obj).then((response) => {
          if (response.code == 0) {
            that.$message({"duration": '800', message: '保存成功', type: 'success', customClass: 'zZindex'});
            that.go()
          }
        })
      },

      getFormData: function () {
        if (this.$refs.generateForm) {
          this.$refs.generateForm.getData().then(data => {
            this.startForm.formData = JSON.stringify(data)
            this.formData_e = null
            return data
          }).catch(e => {
            this.formData_e = e;
          })
        }

      },
      go: function () {
        if (this.formIndex) {
          this.jsonData = {}
          this.editData = {}
          this.formIndex = false;
          //首页过来的
          this.$emit('closeEvent', true)


        } else {
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.go(-1)
        }

      },
      start: function (item) {
        this.$router.push({name: 'handleHisTaskDetails', query: {t: new Date().getTime()}})
      },
      loadWfModule: function () {
        loadWfModule().then((response) => {
          this.tableData = response.data
        })
      },
      getData: function () {
        getStartBtn(this.modelKey).then((response) => {

          this.taskBtns = response.data
          this.startForm.defId = response.defId
          this.startForm.modelId = response.modelId
          this.xml= response.xml
          var url = this.baseURL + "view/def.html?&modelId=" + response.modelId+"&t="+new Date()
          this.viewImageModelerTmpSrc = url;
          if (response.bta) {
            this.attachmentForm.createBy = response.bta.createBy
            this.attachmentForm.createTime = response.bta.createTime
            this.attachmentForm.procDefId = response.bta.procDefId
            this.attachmentForm.userNo = response.bta.userNo
          }
          if (response.existBpmTaskAttachment) {
            this.attachmentForm.changeContent = response.existBpmTaskAttachment.changeContent
            this.attachmentForm.id = response.existBpmTaskAttachment.id
            this.startForm.attachmentId = this.attachmentForm.id;
            if (response.existBpmTaskAttachment.bpmTaskAttachmentDetailedList) {
              this.fileList = response.existBpmTaskAttachment.bpmTaskAttachmentDetailedList;
            }
          }else{
            //不存在数据
            this.startForm.attachmentId=""
            this.attachmentForm.id=""
            this.attachmentForm.changeContent=""
            this.fileList=[]
          }

          if (response.sysTypeEntity) {
            this.startForm.typeTitle = response.sysTypeEntity.title
            this.startForm.groupId = response.sysTypeEntity.id
            this.startForm.typeKey = response.sysTypeEntity.typeKey
          }

          renderStartForm(this.startForm.defId).then((response) => {
            if (response.code == 0) {
              this.jsonData = JSON.parse(response.data)
              this.built = response.built
              if (response.editData) {
                this.editData = JSON.parse(response.editData)
              }
            } else {
              this.go()
            }
          })

          this.isSpinShow = false
          this.$nextTick(() => {
          })
        })
      }

    }

  }

</script>
<style lang="scss" scoped>
  .task-card {
    margin-top: 10px;
  }

  .item {
    display: block;
    width: 311px;
    float: left;
    margin-left: 20px;
    box-shadow: 0 0 20px 0 rgba(204, 207, 227, .45);
    margin-bottom: 10px;

  }

  .left {
    font-size: 16px;
    color: #575757;
  }

  img {
    width: 60px;
    height: 60px;
  }

  .container {
    height: auto !important;
    min-height: 450px;
  }

  .zZindex {
    z-index: 3000 !important;
  }
</style>
